# -*- coding: UTF-8 -*-
# __author__ = '10459'

from flask import current_app

from app.libs.httpresp import HTTPRESP


class YuShuBook:
    isbn_url = "http://yushu.talelin.com/v2/book/isbn/{}"
    keyword_url="http://yushu.talelin.com/v2/book/search?q={}&count={}&start={}"


    # isbn_url = "http://t.yushu.im/v2/book/isbn/{}"
    # keyword_url = "http://t.yushu.im/v2/book/search?q={}&count={}&start={}"

    def __init__(self):
        self.total = 0
        self.books = []

    def __fill_single(self, data):
        if data:
            self.total = 1
            self.books.append(data)

    def __fill_collection(self, data):
        self.total = data['total']
        self.books = data['books']

    def search_by_isbn(self, isbn):
        # 类变量可以使用实例变量访问，一般在实例方法中，使用实例self访问即可，当然类访问也行
        # 类可以访问静态方法，实例也可以访问，类与实例都可以访问类方法（类方法其他语言实例不一定能访问）
        url = self.isbn_url.format(isbn)
        # __dict__
        result = HTTPRESP.get(url)
        try:
            self.__fill_single(result)
        except Exception as e:
            print(e)

    def search_by_keyword(self, keyword, page=1):
        url = self.keyword_url.format(keyword, current_app.config['PER_PAGE'], self.calculate_start(page))
        result = HTTPRESP.get(url)
        self.__fill_collection(result)

    def calculate_start(self, page):
        return (page - 1) * current_app.config['PER_PAGE']

    @property
    def first(self):
        return self.books[0] if self.total >= 1 else "取不到数据喔"
